<!DOCTYPE html>
<html lang="zh-cn">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>表单事件</title>
    <style>
      form > div {
        margin: 10px;
      }
      .error-msg {
        color: red;
      }
    </style>
  </head>
  <body>
    <form name="regForm" id="regForm">
      <div>
        用户名: <input type="text" name="username" value="OuO" />
        <span class="error-msg" hidden>用户名不能为空</span>
      </div>
      <div>
        密码: <input type="password" name="password" value="aa123456" />
      </div>
      <div>
        性别:
        <select name="gender">
          <option value="male" selected>男</option>
          <option value="female">女</option>
          <option value="other">其他</option>
        </select>
      </div>
      <div>
        爱好:
        <input type="checkbox" name="hobby" value="sport" checked />运动
        <input type="checkbox" name="hobby" value="reading" />阅读
      </div>
      <div>
        <button type="submit">提交</button>
        <button type="reset">重置</button>
      </div>
    </form>
    <script>
      let regForm = document.forms.regForm;
      console.log(regForm.username.value);
      console.log(regForm.password.value);
      console.log(regForm.gender.value);
      console.log(regForm.hobby);

      regForm.hobby.forEach((it) => {
        if (it.checked) console.log(it.value);
      });

      regForm = document.getElementById("regForm");
      const username = regForm.querySelector("input[name = 'username']");
      username.addEventListener("blur", (event) => {
        if (!username.value) {
          const errorMsg = username.closest("div").querySelector(".error-msg");
          errorMsg.hidden = false;
        }
      });
      username.addEventListener("focus", (event) => {
        const errorMsg = username.closest("div").querySelector(".error-msg");
        errorMsg.hidden = true;
      });
      username.addEventListener("keydown", (event) => {
        if (event.key === "Enter") {
          username.blur();
          regForm.password.focus();
        }
      });

      username.addEventListener("input", (event) => {
        console.log(username.value);
      });
      username.addEventListener("change", (event) => {
        console.log("change");
      });
      regForm.gender.addEventListener("change", (event) => {
        console.log(regForm.gender.value);
      });
      regForm.hobby.forEach((it) => {
        it.addEventListener("change", (event) => {
          console.log(it.checked);
        });
      });

      regForm.addEventListener("submit", (event) => {
        event.preventDefault();
        const formData = new FormData(regForm);
        const formObj = Object.fromEntries(formData);
        formObj.hobby = formData.getAll("hobby");
        console.log(formObj);
      });
    </script>
  </body>
</html>
